package com.sduept.nwld.dataview.controller.core;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.faces.view.ViewScoped;
import javax.inject.Named;

import org.primefaces.PrimeFaces;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.UploadedFile;
import org.springframework.beans.factory.annotation.Autowired;

import com.sduept.bigdata.document.core.CommonDocumentProperties;
import com.sduept.bigdata.document.entity.core.RecordAttachment;
import com.sduept.bigdata.document.services.RecordAttachmentManager;
import com.sduept.bigdata.web.jsf.controller.AbstractController;
import com.sduept.generator.ObjectId;

@Named
@ViewScoped
public class FileUploadManagerController extends AbstractController {

	private static final long serialVersionUID = 643274223355668542L;

	@Autowired
	private CommonDocumentProperties pros;
	private String uploadFileType = "";
	private List<RecordAttachment> ras = new ArrayList<RecordAttachment>();
	private String oid = null;
	private String path = null;
	
	@Autowired
	private RecordAttachmentManager rman ;

	@PostConstruct
	public void init() {
		oid = getParameter("oid");
		path = getParameter("path");
	}

	public void handleFileUpload(FileUploadEvent event) {
		UploadedFile file = event.getFile();
		String houzhuiming = file.getFileName().substring(file.getFileName().lastIndexOf("."));
		String id = ObjectId.get().toString();
		String dirFileName = id + houzhuiming;
		String filePath = path;
		if (filePath == null)
			filePath = pros.getDocumentPath() + dirFileName;
		else
			filePath += dirFileName;
		try {
			FileOutputStream fos = new FileOutputStream(filePath);
			fos.write(file.getContents());
			fos.close();
			RecordAttachment ra = new RecordAttachment();
			ra.setName(dirFileName);
			ra.setDescription(file.getFileName());
			ra.setOid(oid);
			ra.setType(uploadFileType);
			ra.setUploadDate(new Date());
			ra.setPath(dirFileName);
			ra = rman.createOrUpdateRecordAttachment(ra);
			if (ra != null && ra.getId() != null) {
				ras.add(ra);
			}
		} catch (IOException ee) {
			ee.printStackTrace();
		}
		addSuccessMessage("附件上传成功，请确认");
	}

	public void returnRecordAttachments() {
		if (ras != null) {
			PrimeFaces.current().dialog().closeDynamic(ras);
		}
	}

	public String getUploadFileType() {
		return uploadFileType;
	}

	public void setUploadFileType(String uploadFileType) {
		this.uploadFileType = uploadFileType;
	}

	public List<RecordAttachment> getRas() {
		return ras;
	}

	public void setRas(List<RecordAttachment> ras) {
		this.ras = ras;
	}

	public String getOid() {
		return oid;
	}

	public void setOid(String oid) {
		this.oid = oid;
	}

	public String getPath() {
		return path;
	}

	public void setPath(String path) {
		this.path = path;
	}

}
